package demo.practice.dfs;

public class P79 {

    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || board[0].length == 0 || word == null || word.length() == 0)
            return true;

        char st = word.charAt(0);
        int h = board.length;
        int w = board[0].length;
        char[] wchars = word.toCharArray();

        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                char c = board[i][j];
                if (c == st) {
                    int[][] visited = new int[h][w];
                    if (dfs(board, visited, i, j, wchars, 0))
                        return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, int[][] visited, int i, int j, char[] wchars, int w) {
        if (visited[i][j] == 1 || board[i][j] != wchars[w]) {
            return false;
        }

        if (w == wchars.length - 1) {
            return true;
        }

        visited[i][j] = 1;
        if (i + 1 < board.length && dfs(board, visited, i + 1, j, wchars, w + 1)) {
            return true;
        }
        if (i - 1 >= 0 && dfs(board, visited, i - 1, j, wchars, w + 1)) {
            return true;
        }
        if (j - 1 >= 0 && dfs(board, visited, i, j - 1, wchars, w + 1)) {
            return true;
        }
        if (j + 1 < board[0].length && dfs(board, visited, i, j + 1, wchars, w + 1)) {
            return true;
        }

        visited[i][j] = 0;
        return false;
    }

}
